using UnityEngine;
using System.Text;

namespace BF
{
    public static class TransformExtension
    {
        public static Transform Reset(this Transform self)
        {
            if (self == null) return self;
            self.localPosition = Vector3.zero;
            self.localRotation = Quaternion.identity;
            self.localScale = Vector3.one;
            return self;
        }

        public static Transform CopyInfo(this Transform self, Transform targetTransform)
        {
            if (self == null || targetTransform == null) return self;
            self.SetParent(targetTransform.parent);
            self.localPosition = targetTransform.localPosition;
            self.localRotation = targetTransform.localRotation;
            self.localScale = targetTransform.localScale;

            return self;
        }

        public static string GetPath(this Transform self)
        {
            if (self == null)
                return null;

            StringBuilder sb = new StringBuilder(self.name);
            for (Transform temp = self.parent; temp != null; sb.Insert(0, temp.name + "/"), temp = temp.parent) ;
            return sb.ToString();
        }

        public static Rect GetWordRect(this Transform self)
        {
            if (self == null || !(self is RectTransform))
            {
                throw new System.NullReferenceException("[GetWordRect] transform is null");
            }
            Vector2 size = Vector2.Scale(self.As<RectTransform>().rect.size, self.lossyScale);
            return new Rect((Vector2)self.position - (size * 0.5f), size);
        }

        public static bool IsPositionIn(this Transform self, Vector3 position, bool worldSpace = false, float rectScale = 1)
        {
            if (!worldSpace)
                if (Camera.main != null)
                    position = Camera.main.ScreenToWorldPoint(position);

            Rect rect = self.GetWordRect();
            Rect scaleRect = new Rect(rect.center - rect.size * rectScale / 2, rect.size * rectScale);
            return scaleRect.Contains(position);
        }
    }
}
